const settingsController = function (HttpService, AuthService) {
  "ngInject";

  const vm = this;

  vm.activeTab = "profile";

  vm.userProfile = {
    name: "管理员",
    email: "admin@example.com",
    phone: "13800138000",
    department: "IT部门",
    role: "administrator",
  };

  vm.systemSettings = {
    siteName: "工单管理系统",
    defaultLanguage: "zh-CN",
    timezone: "Asia/Shanghai",
    emailNotifications: true,
    autoAssign: false,
    maxFileSize: 10,
  };

  vm.notificationSettings = {
    emailNewTicket: true,
    emailTicketUpdate: true,
    emailTicketComplete: false,
    pushNotifications: true,
    dailyDigest: true,
  };

  vm.setActiveTab = function (tab) {
    vm.activeTab = tab;
  };

  vm.saveProfile = function () {
    if (vm.profileForm.$valid) {
      console.log("保存用户资料:", vm.userProfile);
      alert("用户资料保存成功！");
    } else {
      alert("请填写正确的用户信息");
    }
  };

  vm.saveSystemSettings = function () {
    if (vm.systemForm.$valid) {
      console.log("保存系统设置:", vm.systemSettings);
      alert("系统设置保存成功！");
    } else {
      alert("请填写正确的设置信息");
    }
  };

  vm.saveNotificationSettings = function () {
    console.log("保存通知设置:", vm.notificationSettings);
    alert("通知设置保存成功！");
  };

  vm.changePassword = function () {
    if (vm.passwordForm.$valid) {
      if (vm.newPassword !== vm.confirmPassword) {
        alert("新密码与确认密码不一致");
        return;
      }
      console.log("修改密码");
      alert("密码修改成功！");

      vm.oldPassword = "";
      vm.newPassword = "";
      vm.confirmPassword = "";
      vm.passwordForm.$setPristine();
      vm.passwordForm.$setUntouched();
    } else {
      alert("请填写正确的密码信息");
    }
  };

  // 权限检查方法
  vm.hasRole = function (roles) {
    const user = AuthService.getCurrentUser();
    if (!user || !roles || roles.length === 0) return true;
    return roles.includes(user.role);
  };

  // ========== 字典配置相关方法 ==========

  // 初始化字典数据
  vm.lookupTypes = [];
  vm.lookupItems = [];
  vm.selectedTypeId = null;
  vm.selectedTypeName = "";
  vm.lookupSearch = "";
  vm.selectedLookupType = "";
  vm.lookupStatusFilter = "";

  // 字典表单数据
  vm.lookupTypeForm = {};
  vm.lookupItemForm = {};

  // 获取字典类型列表
  vm.loadLookupTypes = function () {
    HttpService.get("/lookup-types", {
      page: 1,
      pageSize: 100,
      search: vm.lookupSearch,
      status: vm.lookupStatusFilter,
    })
      .then(function (response) {
        if (response.data.success) {
          vm.lookupTypes = response.data.data.items;
        } else {
          console.error("获取字典类型失败:", response.data.message);
          alert("获取字典类型失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("获取字典类型错误:", error);
        alert("获取字典类型失败");
      });
  };

  // 获取字典项列表
  vm.loadLookupItems = function (typeId) {
    if (!typeId) {
      vm.lookupItems = [];
      return;
    }

    HttpService.get("/lookup-items", {
      page: 1,
      pageSize: 100,
      type_id: typeId,
    })
      .then(function (response) {
        if (response.data.success) {
          vm.lookupItems = response.data.data.items;
        } else {
          console.error("获取字典项失败:", response.data.message);
          alert("获取字典项失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("获取字典项错误:", error);
        alert("获取字典项失败");
      });
  };

  // 选择字典类型
  vm.selectType = function (type) {
    vm.selectedTypeId = type.id;
    vm.selectedTypeName = type.name;
    vm.loadLookupItems(type.id);
  };

  // 搜索字典
  vm.searchLookups = function () {
    vm.loadLookupTypes();
  };

  // 按类型筛选
  vm.filterByType = function () {
    if (vm.selectedLookupType) {
      vm.selectType({ id: vm.selectedLookupType });
    } else {
      vm.selectedTypeId = null;
      vm.selectedTypeName = "";
      vm.lookupItems = [];
    }
  };

  // 按状态筛选
  vm.filterByStatus = function () {
    vm.loadLookupTypes();
    if (vm.selectedTypeId) {
      vm.loadLookupItems(vm.selectedTypeId);
    }
  };

  // 重置筛选条件
  vm.resetLookupFilters = function () {
    vm.lookupSearch = "";
    vm.selectedLookupType = "";
    vm.lookupStatusFilter = "";
    vm.selectedTypeId = null;
    vm.selectedTypeName = "";
    vm.lookupItems = [];
    vm.loadLookupTypes();
  };

  // 显示创建字典类型模态框
  vm.showCreateTypeModal = function () {
    vm.lookupTypeForm = {
      code: "",
      name: "",
      description: "",
      sort_order: 0,
      status: 1,
    };

    // 使用 Bootstrap 5 API 显示模态框
    if (typeof bootstrap !== "undefined") {
      const modal = new bootstrap.Modal(
        document.getElementById("lookupTypeModal")
      );
      modal.show();
    } else {
      // 回退到 jQuery 方式
      $("#lookupTypeModal").modal("show");
    }
  };

  // 编辑字典类型
  vm.editType = function (type) {
    vm.lookupTypeForm = angular.copy(type);

    if (typeof bootstrap !== "undefined") {
      const modal = new bootstrap.Modal(
        document.getElementById("lookupTypeModal")
      );
      modal.show();
    } else {
      $("#lookupTypeModal").modal("show");
    }
  };

  // 保存字典类型
  vm.saveLookupType = function () {
    if (!vm.typeForm.$valid) {
      alert("请填写完整的字典类型信息");
      return;
    }

    const isEdit = !!vm.lookupTypeForm.id;
    const url = isEdit
      ? `/lookup-types/${vm.lookupTypeForm.id}`
      : "/lookup-types";
    const method = isEdit ? "PUT" : "POST";

    HttpService[method.toLowerCase()](url, vm.lookupTypeForm)
      .then(function (response) {
        if (response.data.success) {
          alert(isEdit ? "字典类型更新成功" : "字典类型创建成功");
          vm.loadLookupTypes();

          // 关闭模态框
          if (typeof bootstrap !== "undefined") {
            const modal = bootstrap.Modal.getInstance(
              document.getElementById("lookupTypeModal")
            );
            modal.hide();
          } else {
            $("#lookupTypeModal").modal("hide");
          }
        } else {
          alert("操作失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("保存字典类型错误:", error);
        alert("保存字典类型失败");
      });
  };

  // 删除字典类型
  vm.deleteType = function (type) {
    if (!confirm(`确定要删除字典类型"${type.name}"吗？`)) {
      return;
    }

    if (type.is_system) {
      alert("系统预置字典类型不允许删除");
      return;
    }

    HttpService.delete(`/lookup-types/${type.id}`)
      .then(function (response) {
        if (response.data.success) {
          alert("字典类型删除成功");
          vm.loadLookupTypes();
          if (vm.selectedTypeId === type.id) {
            vm.selectedTypeId = null;
            vm.selectedTypeName = "";
            vm.lookupItems = [];
          }
        } else {
          alert("删除失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("删除字典类型错误:", error);
        alert("删除字典类型失败");
      });
  };

  // 显示创建字典项模态框
  vm.showCreateItemModal = function () {
    vm.lookupItemForm = {
      type_id:
        vm.selectedTypeId ||
        (vm.lookupTypes.length > 0 ? vm.lookupTypes[0].id : ""),
      parent_id: null,
      code: "",
      name: "",
      value: "",
      description: "",
      sort_order: 0,
      status: 1,
    };

    if (typeof bootstrap !== "undefined") {
      const modal = new bootstrap.Modal(
        document.getElementById("lookupItemModal")
      );
      modal.show();
    } else {
      $("#lookupItemModal").modal("show");
    }
  };

  // 编辑字典项
  vm.editItem = function (item) {
    vm.lookupItemForm = angular.copy(item);

    if (typeof bootstrap !== "undefined") {
      const modal = new bootstrap.Modal(
        document.getElementById("lookupItemModal")
      );
      modal.show();
    } else {
      $("#lookupItemModal").modal("show");
    }
  };

  // 保存字典项
  vm.saveLookupItem = function () {
    if (!vm.itemForm.$valid) {
      alert("请填写完整的字典项信息");
      return;
    }

    const isEdit = !!vm.lookupItemForm.id;
    const url = isEdit
      ? `/lookup-items/${vm.lookupItemForm.id}`
      : "/lookup-items";
    const method = isEdit ? "PUT" : "POST";

    HttpService[method.toLowerCase()](url, vm.lookupItemForm)
      .then(function (response) {
        if (response.data.success) {
          alert(isEdit ? "字典项更新成功" : "字典项创建成功");
          vm.loadLookupTypes(); // 刷新类型列表（更新项目计数）
          if (vm.selectedTypeId) {
            vm.loadLookupItems(vm.selectedTypeId); // 刷新项目列表
          }

          // 关闭模态框
          if (typeof bootstrap !== "undefined") {
            const modal = bootstrap.Modal.getInstance(
              document.getElementById("lookupItemModal")
            );
            modal.hide();
          } else {
            $("#lookupItemModal").modal("hide");
          }
        } else {
          alert("操作失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("保存字典项错误:", error);
        alert("保存字典项失败");
      });
  };

  // 删除字典项
  vm.deleteItem = function (item) {
    if (!confirm(`确定要删除字典项"${item.name}"吗？`)) {
      return;
    }

    if (item.is_system) {
      alert("系统预置字典项不允许删除");
      return;
    }

    HttpService.delete(`/lookup-items/${item.id}`)
      .then(function (response) {
        if (response.data.success) {
          alert("字典项删除成功");
          vm.loadLookupTypes(); // 刷新类型列表（更新项目计数）
          if (vm.selectedTypeId) {
            vm.loadLookupItems(vm.selectedTypeId); // 刷新项目列表
          }
        } else {
          alert("删除失败: " + response.data.message);
        }
      })
      .catch(function (error) {
        console.error("删除字典项错误:", error);
        alert("删除字典项失败");
      });
  };

  // 获取父级选项（用于字典项层级选择）
  vm.getParentOptions = function () {
    if (!vm.lookupItemForm.type_id || !vm.lookupItems) {
      return [];
    }

    // 获取同类型的其他项目作为父级选项（排除自己和自己的子级）
    return vm.lookupItems.filter(function (item) {
      return (
        item.type_id == vm.lookupItemForm.type_id &&
        item.id !== vm.lookupItemForm.id
      );
    });
  };

  // 生成范围数组（用于层级缩进）
  vm.range = function (n) {
    return new Array(n);
  };

  // 监听 activeTab 变化，当切换到字典配置时加载数据
  vm.$onInit = function () {
    // 监听 activeTab 变化
    vm.$watch = vm.$watch || function () {};

    // 手动处理 activeTab 变化
    vm.originalSetActiveTab = vm.setActiveTab;
    vm.setActiveTab = function (tab) {
      vm.activeTab = tab;
      if (tab === "lookups") {
        vm.loadLookupTypes();
      }
    };
  };
};

const settingsComponent = {
  templateUrl: "src/app/pages/settings/settings.template.html",
  controller: settingsController,
};

function initSettingsController() {
  const angular = window.angular;

  if (!angular) {
    console.error("Angular 未找到，无法初始化设置控制器模块");
    return;
  }

  angular
    .module("app.pages.settings", [])
    .component("settingsPage", settingsComponent);
}

// Listen for vendor libs loaded event
window.addEventListener("vendorLibsLoaded", () => {
  initSettingsController();
});

// If Angular already loaded, init directly
if (window.angular) {
  initSettingsController();
}
